// pages/health/health_detail.js
const api = require("../../request/api")
const request = require("../../request/request")
const util = require("../../utils/util")
const App = getApp();
var WxParse = require('../../wxParse/wxParse.js');
Page({

    /**
     * 页面的初始数据
     */
    data: {
        barHeight: App.globalData.paddingTop,

        uid: '',
        article_id: 0,
        // 分享链接进入得到的sid
        getsid: '',
        // 作为分享者传出的sid
        sharesid: '',
        // 是否分享进入页面的标识
        // isShare: true,

        page: 1,
        page_size: 10,
        detail_data: {},
        article_list: [],
        content: '',
        styledata: {
            "bg_color": "white",
            "color": "#000",
            "leftflag": true,
            "homeflag": true,
            "name": "详情",
        },

        options: {}
    },

    /**
     * 生命周期函数--监听页面加载
     */
    async onLoad(options) {
        console.log('healthy-options', options);
        this.init_data(options)

        await this.get_article_detail()
        await this.get_article_list()
        await this.queryWmemberInfo()
        await this.load_acode()

        // 用户通过分享链接进入才会有的操作
        // 用于积累分享积分、绑定分销上下级关系（nobind=0）
        let { sid, nobind } = options
        if (sid) {
            this.getsid = sid
            this.nobind = nobind

            console.log("health-sid-nobind", sid, nobind);
            this.sendShareInfo()
        }
    },

    // 初始化数据
    init_data(options) {
        this.setData({
            uid: App.globalData.uid,
            article_id: options.id,
            VipGrade: App.globalData.VipGrade,
            options
        })
    },

    go_home() {
        wx.switchTab({
            url: '/pages/home/home',
        })

    },
    get_article_list() {
        let params = {
            page: 1,
            pageSize: 3
        }
        request.post(api.articlelist, params).then(res => {
            this.setData({
                article_list: res
            })
        })
    },
    go_detail(e) {
        let id = e.currentTarget.dataset.id
        wx.navigateTo({
            url: '/pages/health/health_detail?id=' + id,
        })
    },
    go_tongue() {
        wx.navigateTo({
            url: '/pages/tongue/tongue',
        })
    },
    go_good_detail() {
        let id = this.data.detail_data.source_url
        wx.navigateTo({
            url: '/pages/good/detail?id=' + id,
        })
    },

    // 获取文章详情
    async get_article_detail() {
        let params = {
            id: this.data.article_id,
            uid: this.data.uid,
        }
        let res = await request.post(api.articledetail, params)
        this.setData({
            detail_data: res
        })
        this.handle_content(res.content)
        // console.log('res.content', res.content);
    },
    handle_content(content) {
        // 此处的第一个content是与content.nodes相对应的
        // <template is="wxParse" data="{{wxParseData:content.nodes}}" />
        WxParse.wxParse('content', 'html', content, this, 0)
    },

    // 拼接sid并保存到data
    async load_acode() {
        let id = this.data.detail_data.id
        let uid = this.data.uid

        if (!uid) {
            await App.gologin()
            // 朋友圈直接查看页面，无法使用wx.login，所以登录会失败。因此需要这个提示
            if (!App.globalData.uid) {
                util.showToast('前往小程序查看更多健康资讯')
                return
            }
            let sid = App.globalData.uid + 'a' + id + 'a7'
            // this.setData({
            //     sharesid: sid,
            // })
            this.sharesid = sid

        } else {
            let sid = App.globalData.uid + 'a' + id + 'a7'
            // this.setData({
            //     sharesid: sid,
            // })
            this.sharesid = sid

        }
        // console.log('load_acode', this.data.sharesid);
    },

    // 调用分享接口
    async sendShareInfo() {
        let shareRes
        console.log('this.data.uid-detail', this.data.uid);

        // 使用uid方式 无法绑定分销上下级关系
        // 已登录
        // if (this.data.uid) {
        //     shareRes = await request.post(api.sendShare, { uid: this.data.uid, sid: this.getsid })
        //     console.log('shareRes 11111', shareRes);
        // }
        // // 未登录 调用wx.login接口
        // else {
        wx.login({
            success: async res => {
                if (res.code) {
                    let params = {
                        code: res.code,
                        sid: this.getsid,
                        nobind: this.nobind
                    }
                    shareRes = await request.post(api.sendShare, params)
                    console.log('shareRes 22222', shareRes);
                }
            },
            fail: err => {
                console.log(err);
            }
        })
        // }
        console.log('shareRes', shareRes);
    },

    // 查询提现人员详细信息
    async queryWmemberInfo() {
        let wDetail = await request.post(api.queryWmemberInfo, { uid: this.data.uid })
        console.log("提现人详情", wDetail);

        // 提现人员详情不显示在页面 无需记录在data中
        this.wDetail = wDetail ? wDetail : {
            allin_moblie: "",
            true_name: ""
        }
    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function (e) {
        let mobile = this.wDetail.allin_moblie
        let truename = this.wDetail.true_name
        let VipGrade = this.data.VipGrade
        let sid = this.sharesid

        // 记录分享次数
        request.postall(api.wxacodeshare, { uid: this.data.uid, sid: sid }).then((res) => {
            console.log(res);
        })


        let nobind = 1 // 正常不绑定关系
        // 文章暂时不做分销关系绑定
        // if (mobile.length == 11 && truename != "" && VipGrade >= 1) {
        //     nobind = 0 // 如果是分销员 则置零 绑定关系
        // }

        let share_path = `/pages/health/health_detail`;
        let sharePath = `/pages/home/home?share=${share_path}&sid=${sid}&id=${this.data.article_id}&nobind=${nobind}`

        let shareObj = {
            title: this.data.detail_data.title,
            path: sharePath,
            imageUrl: this.data.detail_data.cover_img2,
            success: function (res) {
                if (res.errMsg == 'shareAppMessage:ok') {
                    util.showToast('分享成功');
                }
            },
            fail: function (err) {
                console.log(err);
                util.showToast('分享失败');
            },
        };
        console.log(shareObj);

        return shareObj;
    },

    // wx.showShareMenu
    // 无法使用async 会导致分享参数异常
    onShareTimeline() {
        let mobile = this.wDetail.allin_moblie
        let truename = this.wDetail.true_name
        let VipGrade = this.data.VipGrade
        let sid = this.sharesid

        // 记录分享次数
        request.postall(api.wxacodeshare, { uid: this.data.uid, sid: sid }).then((res) => {
            console.log(res);
        })

        // 如果是分销员 这置零绑定关系
        let nobind = 1
        // if (mobile.length == 11 && truename != "" && VipGrade >= 1) {
        //     nobind = 0 // 文章暂时不做分销关系绑定
        // }

        // 不需要路径
        let query = `sid=${sid}&id=${this.data.article_id}&nobind=${nobind}`

        let shareObj = {
            title: this.data.detail_data.title,
            // query: `healthPath=${healthPath}&homePath=${homePath}&sid=${sid}&id=${this.data.article_id}&friend=${true}`,
            // query: `sid=${sid}&id=${this.data.article_id}`,
            query: query,

            imageUrl: this.data.detail_data.cover_img2,
            success: function (res) {
                if (res.errMsg == 'shareAppMessage:ok') {
                    util.showToast('分享成功');
                }
            },
            fail: function (err) {
                console.log(err);
                util.showToast('分享失败');
            },
        };
        return shareObj
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {
    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },
})